// pages/myDistribution/index.js
const common = require('../../utils/common')
const {
  getStats,
  getShopStats
} = require('../../services/distribution')

const defaultPage = {
  curPage: 1,
  pageSize: 10,
  noMore: false
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    query: {
      ...defaultPage
    },
    statusInfo: {},
    shopList: [],
    pInfo: {}, //返回的列表数据，里面包含total等
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu({});
    // 获取我的分销统计数据
    this.getStatus();
    //获取我推荐的店铺
    this.getMyShopStatus(this.data.query);
  },

  // 获取我的分销统计数据
  getStatus() {
    getStats().then(res => {
      this.setData({
        statusInfo: res.data
      });
    }).catch(err => {
      common.log(err);
    })
  },

  //获取我的推荐的店铺
  getMyShopStatus({
    curPage,
    pageSize
  }, pullDownRefresh) {
    let params = {
      curPage: curPage,
      pageSize: pageSize
    }
    getShopStats(params).then(res => {
      if (pullDownRefresh) {
        wx.stopPullDownRefresh({});
      }
      this.hanleShopsData(res, curPage, pullDownRefresh);
    }).catch(err => {
      if (pullDownRefresh) {
        wx.stopPullDownRefresh({});
      }
      common.log(err);
    })
  },

  // 处理返回的店铺数据
  hanleShopsData(res, curPage, pullDownRefresh) {
    //设置数据
    var tmpList = this.data.shopList;
    if (pullDownRefresh) {
      tmpList = [];
    }
    //pageInfo
    var tmpPageInfo = this.data.query;
    if ((!res.page) || res.page.pages <= curPage) {
      tmpPageInfo.noMore = true;
    } else {
      tmpPageInfo.curPage++;
    }
    //list
    if (res.data.length > 0) {
      tmpList = [...tmpList, ...res.data];
    }
    this.setData({
      query: tmpPageInfo,
      pInfo: res.page,
      shopList: tmpList
    });
  },

  queryChange: function (payload, pullDownRefresh) {
    this.setData({
      query: {
        ...this.data.query,
        ...payload
      }
    });
    this.getMyShopStatus(this.data.query, pullDownRefresh);
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.query.noMore) return;
    this.getMyShopStatus(this.data.query);
  }
})
